<?php

namespace UI;

class Form
{

	private $buttons = array ();
	private $rows = array ();
	private $row_index = 0;

	public function __construct($configs = array ())
	{
		foreach ( $configs as $field => $val )
		{
			if ( isset($this->{$field}) )
			{
				$this->{$field} = $val;
			}
		}

		return $this;
	}

	public function add_row($data = array ())
	{
		if ( !isset($data['content']) )
			return $this;

		$this->rows[$this->row_index++] = $this->_get_row_html($data);
		return $this;
	}
	
	public function add_row_html($content)
	{
		if($content !== '')
		{
			$html = '<div class="row-form">' . $content . '</div>';
			$this->rows[$this->row_index++] = $html;
		}
		return $this;
	}

	public function add_btn($button)
	{
		$this->buttons[] = $button;
		return $this;
	}

	public function html()
	{
		$html = '<div class="form-container">';
		$html .= \Form::open(array (
					'action' => isset($this->action) ? $this->action : '',
					'id' => isset($this->id) ? $this->id : uniqid()
		));
		foreach ( $this->rows as $row )
		{
			$html .= $row;
		}
		if ( count($this->buttons) )
		{
			$html .= '<div class="row-form">';
			$html .= '<div class="content buttons">';
			foreach ( $this->buttons as $button )
			{
				$html .= $button;
			}
			$html .= '</div></div>';
		}
		$html .= \Form::close();
		$html .= '</div>';

		return $html;
	}

	private function _get_row_html($data)
	{
		$label = isset($data['label']) ? strip_tags($data['label']) : '';
		$required = isset($data['required']) ? 'required' : '';
		$content = $data['content'];
		$class_content = isset($data['class_content']) ? trip_tags($data['class_content']) : '';
		$html = '<div class="row-form ' . $required . '">
					<div class="label">' . \Form::label($label, null) . '</div>
				</div>
				<div class="row-form">
					<div class="content ' . $class_content . '">' . $content . '</div>
				</div>';
		return $html;
	}

}
